<template>
	<view>

		<uni-forms ref="form" :value="formData" validateTrigger="bind">
			<uni-forms-item class="align-items-center" name="name" label="产品名称" required>
				<uni-easyinput placeholder="名称" v-model="formData.name" />
			</uni-forms-item>
			<uni-forms-item class="align-items-center" name="keywords" label="关键词">
				<uni-easyinput placeholder="关键词" v-model="formData.keywords" trim />
			</uni-forms-item>
			<uni-forms-item class="align-items-center" name="category_id" label="商城分类">
				<view class="category-text">
					<text>{{showCategoryText}}</text>
				</view>
				<view class="set-category-box" @click="toEditCategory">
					<text>设置产品分类</text>
					<wjf-iconfont class="icon-style" code="e61b" color="dodgerblue"></wjf-iconfont>
				</view>
			</uni-forms-item>
			<uni-forms-item class="align-items-center" name="goods_summary" label="产品说明">
				<uni-easyinput type="textarea" placeholder="产品详细描述" v-model="formData.goods_summary" trim />
			</uni-forms-item>
			<uni-forms-item class="align-items-center" name="goods_thumb" label="产品主图" required>
				<cloud-image-alioss uploadDir="henghui/images" v-model="formData.goods_thumb"></cloud-image-alioss>
			</uni-forms-item>
			<uni-forms-item class="align-items-center" name="goods_imgs" label="产品详情图">
				<view class="">
					<text class="font-26 color-555">最多12张图片</text>
				</view>
				<cloud-image-alioss imageNumber="12" uploadDir="henghui/images"
					v-model="formData.goods_imgs"></cloud-image-alioss>
			</uni-forms-item>
			<uni-forms-item name="is_on_sale" label="是否启用" required>
				<switch @change="binddata('is_on_sale', $event.detail.value)" :checked="formData.is_on_sale" />
			</uni-forms-item>

		</uni-forms>
		<view class="button-group">
			<navigator open-type="navigateBack" style="margin-left: 30px;">
				<button style="width: 100px;height: 70rpx;line-height: 70rpx;background-color: #ddd;">返回</button>
			</navigator>
			<button type="primary" style="width: 100px;height: 70rpx;line-height: 70rpx;" @click="submit">提交</button>
		</view>
		<!-- <view class="">
			<button type="default" @click="test">test</button>
		</view> -->
		<uv-modal ref="uvModal" :title="uvModelParam.title" :content='uvModelParam.content' :align="uvModelParam.align"
			:confirmText="uvModelParam.confirmText" :cancelText="uvModelParam.cancelText"
			:showCancelButton="uvModelParam.showCancelButton"></uv-modal>
	</view>
</template>

<script>
	import {
		validator
	} from '@/js_sdk/validator/tian-mall-product.js';

	function getValidator(fields) {
		let reuslt = {}
		for (let key in validator) {
			if (fields.includes(key)) {
				reuslt[key] = validator[key]
			}
		}
		return reuslt
	}
	const db = uniCloud.database()
	const dbCollectionName = 'tian-mall-products';
	import commMixinWjf from '@/common/mixin/common-mixin-wjf.js'
	export default {
		mixins: [commMixinWjf],
		data() {
			return {
				product_id: '',
				formData: {
					name: '',
					keywords: '',
					category_id: [], //产品的商城分类，缓存时为对象数组，保存数据库时为_id数组
					goods_summary: '',
					goods_thumb: '',
					goods_imgs: [],
					is_on_sale: true
				},
				rules: {
					...getValidator(["name", "keywords", "goods_summary", "goods_thumb", "goods_imgs", "is_on_sale"])
				}
			}
		},
		computed:{
			showCategoryText(){
				return this.formData.category_id.map(item=>item.name).join(' > ')
			}
		},
		onLoad(option) {
			this.product_id = option.id
			this.getProductData()
		},
		onReady() {
			this.$refs.form.setRules(this.rules)
		},
		methods: {
			test() {
				console.log(123);
			},
			toEditCategory() {
				uni.navigateTo({
					url: '/pages/shop/edit-category?name=' + this.formData.name,
					events: {
						conformCategory: (categoriesData) => {
							// console.log('接收到事件数据',categoriesData);
							// this.showCategoryText = categoriesData.map(item => item.text).join(' -> ')
							this.formData.category_id = categoriesData.map(item =>{
								return {
									_id:item.value,
									name:item.text
								}
							})
						}
					},
					success: res => {},
					fail: () => {},
					complete: () => {}
				});
			},
			/**
			 * 触发表单提交
			 */
			async submit() {
				// validate
				this.$refs.form.validate().then((res) => {
					console.log(res);
					// this.testFn()
					this.submitForm(res)
					// this.$uvModal({
					// 	content: `请注意输入内容的错误提示，有不合规的输入时无法提交。`,
					// 	align: 'center',
					// })
				}).catch((errors) => {
					console.log(errors);
					this.$uvModal({
						content: `请注意输入内容的错误提示，有不合规的输入时无法提交。`,
						align: 'center',
					})
					return
				})
			},
			submitForm(value) {
				uni.showLoading({
					mask: true
				})
				if (this.formData.category_id.length > 0) {
					value.category_id = this.formData.category_id.map(item => item._id)
				}else{
					value.category_id=[]
				}
				value.last_modify_date=new Date().getTime(); // 获取当前时间戳（毫秒）

				// console.log(value);
				// 使用 clientDB 提交数据
				db.collection(dbCollectionName).doc(this.product_id).update(value).then((res) => {
					uni.showToast({
						title: '修改成功'
					})
					this.getOpenerEventChannel().emit('refreshData')
					setTimeout(() => uni.navigateBack(), 500)
				}).catch((err) => {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					})
				}).finally(() => {
					uni.hideLoading()
				})
			},
			getProductData() {
				const productTab = db.collection(dbCollectionName).where({
					_id: this.product_id
				}).field(
					'name,keywords,goods_summary,goods_thumb,goods_imgs,is_on_sale,category_id').getTemp()
				const categoryTab = db.collection('tian-mall-categories').field('_id,name').getTemp()
				db.collection(productTab, categoryTab).get().then(({
					result
				}) => {
					this.formData = Object.assign(this.formData, result.data[0])
					// this.showCategoryText = this.formData.category_id.map(item => item.name).join(' > ')
					console.log(this.formData);
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.top-btn-box {
		display: flex;
		justify-content: flex-end;
		width: 600px;
		height: 80rpx;

		.top-btn {
			background-color: deepskyblue;
			color: #fff;
		}
	}

	.shop-name-note {
		font-size: 24rpx;
		color: #777;
		padding-left: 20rpx;
	}

	.align-items-center {
		display: flex;
		align-items: center;
	}

	.background {
		background-color: #eee;
		padding: 10rpx;
		border-radius: 6rpx;
	}

	.shop-id-box {
		background-color: #efefef;
		width: 50%;
		height: 100%;
		display: flex;
		justify-content: center;
		align-items: center;
		border-radius: 6rpx;

		text {
			color: #999;
		}
	}

	.button-group {
		width: 100%;
		margin: 50rpx 0;
		padding-bottom: 100rpx;
		display: flex;
		flex-direction: row;
		justify-content: center;
	}

	.location-box {
		display: flex;
		align-items: center;
		margin-top: 30rpx;
	}

	.category-text {
		display: flex;
		flex-wrap: wrap;

		text {
			font-size: 24rpx;
			color: #666;
		}
	}

	.set-category-box {
		margin-top: 20rpx;
		display: flex;
		align-items: center;

		text {
			color: #555;
			font-size: 28rpx;
		}

		.icon-style {
			margin-left: 10rpx;
			color: dodgerblue;
		}
	}
</style>